﻿using System;
using Gtk;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Look52PojieMono;

public partial class MainWindow: Gtk.Window
{
	const string MyTitle = "吾爱破解论坛开放注册信息提取工具";

	public MainWindow () : base (Gtk.WindowType.Toplevel)
	{
		Build ();
	}

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}

	protected void OnBtnSendClicked (object sender, EventArgs e)
	{
		btnSend.Sensitive = false;
		try {
			GetTopics(txtUrl.Text);
		} catch (Exception ex) {
			//MessageDialog dlg = new MessageDialog();
			MessageDialog dlg = new MessageDialog (this, 
				DialogFlags.DestroyWithParent,
				MessageType.Error, 
				ButtonsType.Close, ex.Message);
			//dlg.Text = ex.Message;
			dlg.Title = MyTitle;
			//dlg.Show ();
			dlg.Run();
			//MessageBox.Show(ex.Message, MyTitle);
		}
		btnSend.Sensitive = true;
	}

	void GetTopics(string url)
	{
		double nearestDays = 365.0;
		WebRequest wr = HttpWebRequest.Create(url);
		WebResponse res = wr.GetResponse();
		StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("gbk"));
		string resStr = sr.ReadToEnd();
		sr.Close();

		Gtk.TextBuffer buffer = txtSourceCode.Buffer;
		buffer.Text = resStr;
		Regex re = new Regex(@"<a href=""(http://www.52pojie.cn/thread-\d+-1-1.html)"".*? onclick=""atarget\(this\)"" class=""s xst"">(.+?)</a>", RegexOptions.Multiline);
		MatchCollection mc = re.Matches(resStr);
		//			MessageBox.Show("找到" + mc.Count.ToString() + "个帖子\r\n" + @"<tbody id=""normalthread_\d+"">(.+)</tbody>");

		List<Topic> topics = new List<Topic>();
		List<Topic> regTopics = new List<Topic>();
		foreach (Match m in mc)
		{
			GroupCollection gc = m.Groups;
			string sUrl = gc[1].Value;
			string sTitle = gc[2].Value;
			//				lstTopic.Items.Add(sTitle);
			topics.Add(new Topic(sTitle, sUrl));
			if (sTitle.Contains("【开放注册公告】"))
			{
				//					lstOpenRegist.Items.Add(sTitle);
				regTopics.Add(new Topic(sTitle, sUrl));
				Regex r1 = new Regex(@"(\d+年\d+月\d+日)");
				Regex r2 = new Regex(@"(\d+)年.*?([暑|寒])假");
				Regex r3 = new Regex(@"(\d+)年.*?光棍节");
				Match mm = r1.Match(sTitle);
				string retDate = "";
				if (mm.Success)
				{
					retDate = mm.Groups[1].Value;
				}
				else
				{
					mm = r2.Match(sTitle);
					if (mm.Success)
					{
						retDate = mm.Groups[1].Value;
						if (mm.Groups[2].Value.Equals("暑"))
							retDate += "年7月7日";
						else
							retDate += "年2月1日";
					}
					else
					{
						mm = r3.Match(sTitle);
						if (mm.Success)
							retDate = mm.Groups[1].Value + "年11月11日";
					}
				}

				if (retDate.Length > 0)
				{
					DateTime dtNew = DateTime.ParseExact(retDate, "yyyy年M月d日", null);
					DateTime dtNow = DateTime.Now;
					//TimeSpan tsNew = dtNew.Ticks;
					//TimeSpan tsNow = dtNow.Ticks;
					//TimeSpan ts = tsNew.Subtract(tsNow).Duration();
					TimeSpan ts = dtNew - dtNow;
					double dDays = ts.TotalDays;
					if (Math.Abs(dDays) < Math.Abs(nearestDays))
					{
						nearestDays = dDays;
					}
				}
			}
		}

		if (nearestDays < 365.0)
		{
			string sTit = MyTitle;
			if (nearestDays >= 1.0)
			{
				sTit += " (距下一次开放注册还有" + Math.Ceiling(nearestDays).ToString() + "天)";
			}
			else if (nearestDays < 0)
			{
				sTit += " (上次开放注册已过" + Math.Ceiling(Math.Abs(nearestDays)).ToString() + "天)";
			}
			else
			{
				sTit += " (今日开放注册！！！)";
			}
			this.Title = sTit;
		}

		// ListBox控件实现
		TreeStore topicStore = new TreeStore(typeof(string), typeof(Topic));
		foreach (Topic tp in topics)
		{
			topicStore.AppendValues(tp.Title, tp);
		}
		lstTopic.Model = topicStore;
		lstTopic.HeadersVisible = false;
		lstTopic.AppendColumn("Title", new CellRendererText(), "text", 0);

		TreeStore regTopicStore = new TreeStore(typeof(string), typeof(Topic));
		foreach (Topic tp in regTopics)
		{
			regTopicStore.AppendValues(tp.Title, tp);
		}
		lstOpenRegist.Model = regTopicStore;
		lstOpenRegist.HeadersVisible = false;
		lstOpenRegist.AppendColumn("Title", new CellRendererText(), "text", 0);
	}

	protected void OnLstTopicRowActivated (object o, RowActivatedArgs args)
	{
		//Console.WriteLine("row {0} was doubleclicked", args.Path);	// 得到选中行的下标
		TreeIter iter;
		lstTopic.Selection.GetSelected(out iter);	// 得到选中的项目的迭代器
		//lstTopic.Model.GetIter (out iter, args.Path);	// 上面这行用本行代替可能更标准一些
		Topic tp = (Topic)lstTopic.Model.GetValue (iter, 1);	// 使用迭代器获得指定列的内容
		//Console.WriteLine("row {0} was doubleclicked", tp.Url);
		System.Diagnostics.Process.Start("xdg-open", tp.Url);	// 调用系统默认的程序打开网页
	}

	protected void OnLstOpenRegistRowActivated (object o, RowActivatedArgs args)
	{
		TreeIter iter;
		lstOpenRegist.Selection.GetSelected(out iter);	// 得到选中的项目的迭代器
		//lstOpenRegist.Model.GetIter (out iter, args.Path);	// 上面这行用本行代替可能更标准一些
		Topic tp = (Topic)lstOpenRegist.Model.GetValue (iter, 1);	// 使用迭代器获得指定列的内容
		System.Diagnostics.Process.Start("xdg-open", tp.Url);	// 调用系统默认的程序打开网页
	}
}
